/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;


import ModeloLogicoSistema.AdministradorCliente;
import ModeloLogicoSistema.Cliente;
import ModeloLogicoSistema.Validacion;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author debo
 */
public class BuscarCliente extends javax.swing.JDialog {

    private ArrayList<Cliente> clientes = null;
    private AdministradorCliente admCliente;
    private String encabezadosTabla[] = {"ID", "Nombre", "Apellido", "Telefono", "Celular", "Dirección", "Localidad"};
    private boolean aceptado = true;
    Cliente cliente = null;

    /**
     * Creates new form BuscarCliente
     */
    private void cargarTodosLosClientes() throws SQLException {
        this.clientes = null;
        this.clientes = (ArrayList) admCliente.cargarTodosLosClientes();
    }

    boolean fueAceptado() {
        return aceptado;
    }

    void habilitarModificacion() {
        this.jModificar.setVisible(true);
        this.jBtnCancelar.setVisible(true);
        this.jBtnEliminar.setVisible(false);
        this.jAceptar.setVisible(false);
    }

    void habilitarEliminar() {
        this.jBtnEliminar.setVisible(true);
        this.jAceptar.setVisible(false);
        this.jBtnCancelar.setVisible(true);
        this.jModificar.setVisible(false);
    }

    void habilitarBusqueda() {
        this.jBtnEliminar.setVisible(false);
        this.jAceptar.setVisible(true);
        this.jBtnCancelar.setVisible(true);
        this.jModificar.setVisible(false);
    }

    private void cargarDatosEnTabla() {
        DefaultTableModel modelo = (DefaultTableModel) tablaCliente.getModel();
        try {
            cargarTodosLosClientes();
        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
        ListIterator it = this.clientes.listIterator(0);
        while (it.hasNext()) {
            Cliente c = (Cliente) it.next();
            String dir = c.getCalle() + " " + c.getNroCalle();
            String direccion;
            if (c.getPisoNro().length() != 0 & c.getPisoNro() != null) {
                direccion = dir + ", " + c.getPisoNro();
            } else {
                direccion = dir;
            }
            String domicilio = direccion + c.getPisoNro();
            Object[] fila = {c.getNroCliente(), c.getNombre(), c.getApellido(),
                c.getTelFijo(), c.getCel(), direccion, c.getLocalidad()};
            modelo.addRow(fila);
        }
    }

    private void actualizarTablaCliente() throws SQLException {
        DefaultTableModel modeloTabla = new DefaultTableModel();
        modeloTabla.setColumnIdentifiers(encabezadosTabla);
        tablaCliente.setModel(modeloTabla);
        cargarDatosEnTabla();
    }

    private void actualizarTablaBusquedaCliente() throws SQLException {

        DefaultTableModel modeloTabla = (DefaultTableModel) this.tablaCliente.getModel();
        int canFilas = modeloTabla.getRowCount();
        int fila = 0;
        for (int i = 0; i < canFilas; i++) {
            modeloTabla.removeRow(fila);
        }
        cargarDatosBusqueda();
    }

    private void cargarDatosBusqueda() {
        DefaultTableModel modelo = (DefaultTableModel) this.tablaCliente.getModel();
        ListIterator it = this.clientes.listIterator(0);
        while (it.hasNext()) {
            Cliente c = (Cliente) it.next();
            String dir = c.getCalle() + " " + c.getNroCalle();
            String direccion;
            if (c.getPisoNro().length() != 0 & c.getPisoNro() != null) {
                direccion = dir + ", " + c.getPisoNro();
            } else {
                direccion = dir;
            }
            String domicilio = direccion + c.getPisoNro();
            Object[] fila = {c.getNroCliente(), c.getNombre(), c.getApellido(),
                c.getTelFijo(), c.getCel(), direccion, c.getLocalidad()};
            modelo.addRow(fila);
        }
    }

    /**
     * Considero que cada elemento de la tabla ocupa la misma posición que en la
     * lista.
     */
    Cliente getClienteSeleccionado() {
        int posicion = this.tablaCliente.getSelectedRow();
        if (posicion != -1) {
            this.cliente = this.clientes.remove(posicion);
            return this.cliente;
        }
        return null;
    }

    public BuscarCliente(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.aceptado = false;
        this.clientes = new ArrayList<>();
        this.setLocationRelativeTo(null);
        DefaultTableModel modeloTabla = new DefaultTableModel();
        modeloTabla.setColumnIdentifiers(encabezadosTabla);
        tablaCliente.setModel(modeloTabla);

        try {
            this.admCliente = new AdministradorCliente();
            this.clientes = (ArrayList) admCliente.cargarTodosLosClientes();
            cargarDatosEnTabla();
        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jBtnModificar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaCliente = new javax.swing.JTable();
        jBtnCancelar = new javax.swing.JButton();
        btnRefrescar = new javax.swing.JButton();
        jBuscar = new javax.swing.JButton();
        jCBBusqueda = new javax.swing.JComboBox();
        jBtnEliminar = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jAceptar = new javax.swing.JButton();
        jAceptar.setVisible(false);
        jModificar = new javax.swing.JButton();

        jBtnModificar.setText("Modificar");
        jBtnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnModificarActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Buscar Cliente");

        tablaCliente.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tablaCliente);

        jBtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/cancelar.png"))); // NOI18N
        jBtnCancelar.setText("Cancelar");
        jBtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnCancelarActionPerformed(evt);
            }
        });

        btnRefrescar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/refresh.png"))); // NOI18N
        btnRefrescar.setText("Refrescar");
        btnRefrescar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefrescarActionPerformed(evt);
            }
        });

        jBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Buscar.png"))); // NOI18N
        jBuscar.setText("Buscar");
        jBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBuscarActionPerformed(evt);
            }
        });

        jCBBusqueda.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "IdCliente", "Nombre", "Apellido", "Telefono", "Celular", "" }));
        jCBBusqueda.setSelectedItem("idCliente");
        jCBBusqueda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCBBusquedaActionPerformed(evt);
            }
        });

        jBtnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/quitar.png"))); // NOI18N
        jBtnEliminar.setText("Eliminar");
        jBtnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnEliminarActionPerformed(evt);
            }
        });

        jAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Guardar.png"))); // NOI18N
        jAceptar.setText("Aceptar");
        jAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jAceptarActionPerformed(evt);
            }
        });

        jModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/Modificar.png"))); // NOI18N
        jModificar.setText("Modificar");
        jModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jModificarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jBtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jBtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jCBBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnRefrescar, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBuscar)
                    .addComponent(jCBBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnRefrescar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBtnCancelar)
                    .addComponent(jBtnEliminar)
                    .addComponent(jAceptar)
                    .addComponent(jModificar))
                .addContainerGap())
        );

        jAceptar.getAccessibleContext().setAccessibleName("BtnAceptar");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCancelarActionPerformed

        this.dispose();
    }//GEN-LAST:event_jBtnCancelarActionPerformed

    private void btnRefrescarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefrescarActionPerformed
        try {
            this.cargarTodosLosClientes();
            this.actualizarTablaBusquedaCliente();

        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_btnRefrescarActionPerformed

    private void jCBBusquedaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCBBusquedaActionPerformed
    }//GEN-LAST:event_jCBBusquedaActionPerformed

    private void jBtnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnModificarActionPerformed
        this.cliente = this.getClienteSeleccionado();
        try {
            if (this.cliente == null) {
            } else {
                ModificacionCliente modCliente = new ModificacionCliente(null, rootPaneCheckingEnabled, cliente);
                modCliente.setVisible(true);
                this.actualizarTablaCliente();
            }

        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }


    }//GEN-LAST:event_jBtnModificarActionPerformed

    private void jBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBuscarActionPerformed
        String eleccionBusqueda = jCBBusqueda.getSelectedItem().toString();

        this.clientes = new ArrayList<>();
        if (eleccionBusqueda.equalsIgnoreCase("IdCliente")) {
            if (!jTextField1.getText().isEmpty()) {
                try {
                    if (Validacion.cantidadesValidas(jTextField1.getText())) {
                        Integer valorBusqueda = new Integer(jTextField1.getText());
                        Cliente cliente = this.admCliente.buscarClientePorNum(valorBusqueda);
                        if (cliente != null) {
                            clientes.add(cliente);
                            this.actualizarTablaBusquedaCliente();
                        } else {
                            clientes = new ArrayList();
                            this.actualizarTablaBusquedaCliente();
                        }
                    }

                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        if (eleccionBusqueda.equalsIgnoreCase("Nombre")) {

            if (!jTextField1.getText().isEmpty()) {
                String valorBusqueda = jTextField1.getText();
                clientes = (ArrayList<Cliente>) this.admCliente.buscarClientePorNombre(valorBusqueda);
                try {
                    //this.cargarTabla();
                    this.actualizarTablaBusquedaCliente();
                    //this.cargarDatosEnTabla();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        if (eleccionBusqueda.equalsIgnoreCase("Apellido")) {
            if (!jTextField1.getText().isEmpty()) {
                String valorBusqueda = jTextField1.getText();
                clientes = (ArrayList<Cliente>) this.admCliente.buscarClientePorApellido(valorBusqueda);
                try {
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        if (eleccionBusqueda.equalsIgnoreCase("Telefono")) {
            if (!jTextField1.getText().isEmpty()) {
                String valorBusqueda = jTextField1.getText();
                clientes = (ArrayList<Cliente>) this.admCliente.buscarClientePorTel(valorBusqueda);
                try {
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        if (eleccionBusqueda.equalsIgnoreCase("Celular")) {
            if (!jTextField1.getText().isEmpty()) {
                String valorBusqueda = jTextField1.getText();
                clientes = (ArrayList<Cliente>) this.admCliente.buscarClientePorCel(valorBusqueda);
                try {
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                try {
                    this.cargarTodosLosClientes();
                    this.actualizarTablaBusquedaCliente();
                } catch (SQLException ex) {
                    Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
        /*
         if(eleccionBusqueda.equalsIgnoreCase("Direccion")){
         String valorBusqueda=jTextField1.getText();
         String Nro=valorBusqueda.s;
         clientes=(ArrayList<Cliente>) this.admCliente.buscarClientePorDomicilio(valorBusqueda, WIDTH);
         this.cargarTabla();
         }*/
    }//GEN-LAST:event_jBuscarActionPerformed

    private void jBtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnEliminarActionPerformed
        try {
            int opcion = JOptionPane.showConfirmDialog(null, "Esta segudo que desea eliminar este cliente", "Eliminar cliente", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (opcion == JOptionPane.YES_OPTION) {
                this.cliente = this.getClienteSeleccionado();
                this.admCliente.eliminarCliente(cliente.getNroCliente());
                this.actualizarTablaCliente();
            } else {
                return;
            }

        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jBtnEliminarActionPerformed

    private void jAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jAceptarActionPerformed
        this.aceptado = true;
        this.setVisible(false);
    }//GEN-LAST:event_jAceptarActionPerformed

    private void jModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jModificarActionPerformed
        this.cliente = this.getClienteSeleccionado();
        try {
            if (this.cliente == null) {
            } else {
                ModificacionCliente modCliente = new ModificacionCliente(null, rootPaneCheckingEnabled, cliente);
                modCliente.setVisible(true);
                this.actualizarTablaCliente();
            }

        } catch (SQLException ex) {
            Logger.getLogger(BuscarCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jModificarActionPerformed
    /**
     * @param args the command line arguments
     */
    /*public static void main(String args[]) {
     /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    /*        try {
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
     if ("Nimbus".equals(info.getName())) {
     javax.swing.UIManager.setLookAndFeel(info.getClassName());
     break;
     }
     }
     } catch (ClassNotFoundException ex) {
     java.util.logging.Logger.getLogger(BuscarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     } catch (InstantiationException ex) {
     java.util.logging.Logger.getLogger(BuscarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     } catch (IllegalAccessException ex) {
     java.util.logging.Logger.getLogger(BuscarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     } catch (javax.swing.UnsupportedLookAndFeelException ex) {
     java.util.logging.Logger.getLogger(BuscarCliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
     }
     //</editor-fold>

     /* Create and display the dialog */
    /*   java.awt.EventQueue.invokeLater(new Runnable() {
     public void run() {
     BuscarCliente dialog = new BuscarCliente(new javax.swing.JFrame(), true);
     dialog.addWindowListener(new java.awt.event.WindowAdapter() {
     @Override
     public void windowClosing(java.awt.event.WindowEvent e) {
     System.exit(0);
     }
     });
     dialog.setVisible(true);
     }
     });
     }*/
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRefrescar;
    private javax.swing.JButton jAceptar;
    private javax.swing.JButton jBtnCancelar;
    private javax.swing.JButton jBtnEliminar;
    private javax.swing.JButton jBtnModificar;
    private javax.swing.JButton jBuscar;
    private javax.swing.JComboBox jCBBusqueda;
    private javax.swing.JButton jModificar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTable tablaCliente;
    // End of variables declaration//GEN-END:variables
}
